// Copyright (c)  YISH. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Text.RegularExpressions;

namespace NSQL
{
    public class Identifier
    {
        private readonly string _name;
        public readonly bool Delimited;
        public Identifier(string name, bool delimited = false)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("The argument 'name' can not be null or whitespace.");
            }

            _name = name;

            Delimited = delimited || !NameRegex.IsMatch(name);
        }
        
        public static implicit operator Identifier(string identifier)
        {
            return string.IsNullOrWhiteSpace(identifier) ? null : new Identifier(identifier);
        }
        public static implicit operator string(Identifier identifier)
        {
            return identifier?._name;
        }


        public static bool operator ==(Identifier left, Identifier right)
        {
            return  left?.Equals(right) ?? right is null;
        }

        public static bool operator !=(Identifier left, Identifier right)
        {
            return !(left == right);
        }

        public override bool Equals(object obj)
        {
            return obj is Identifier identifier && identifier._name == _name || obj is string s && s == _name;
        }
        private bool Equals(string obj)
        {
            return obj is string s && s == _name;
        }

        public override string ToString() => _name;


        public override int GetHashCode() => _name.GetHashCode();

        private static readonly Regex NameRegex = new Regex(@"^(([a-zA-Z][a-z0-9A-Z_]*)|((\[\{\d+\}\])|(\{\d+\})))$", RegexOptions.Compiled);
    }
}